package com.arvin.faceDetect.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import com.google.mlkit.vision.face.Face

/**
 * 人脸检测结果的叠加显示视图
 * 负责在相机预览上绘制人脸检测框
 */
class FaceOverlayView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    // 绘制人脸框的画笔
    private val paint = Paint().apply {
        color = Color.GREEN      // 框的颜色为绿色
        style = Paint.Style.STROKE  // 绘制空心矩形
        strokeWidth = 3f         // 减小线条宽度
        isAntiAlias = true      // 启用抗锯齿
    }

    // 当前检测到的人脸列表
    private var faces: List<Face> = emptyList()
    // 预览视图的尺寸
    private var previewWidth = 0
    private var previewHeight = 0
    // 原始图像的尺寸
    private var imageWidth = 0
    private var imageHeight = 0
    // 是否使用前置相机
    private var isFrontCamera = true
    // 图像旋转角度
    private var imageRotation = 0
    // 坐标转换矩阵
    private var transformationMatrix = Matrix()
    // 是否需要更新转换矩阵
    private var needUpdateTransformation = true
    // 是否显示人脸框
    private var showFaceRect = true
    // 是否显示眼睛框
    private var showEyeRect = true

    /**
     * 设置是否显示人脸追踪框
     */
    fun setShowFaceRect(show: Boolean) {
        showFaceRect = show
        invalidate()
    }

    /**
     * 设置是否显示眼睛追踪框
     */
    fun setShowEyeRect(show: Boolean) {
        showEyeRect = show
        invalidate()
    }

    /**
     * 更新人脸检测结果
     * @param faces 检测到的人脸列表
     * @param showFaceRect 是否显示人脸框
     * @param imageWidth 原始图像宽度
     * @param imageHeight 原始图像高度
     * @param rotation 图像旋转角度
     * @param isFrontCamera 是否是前置相机
     */
    fun updateFaces(
        faces: List<Face>,
        showFaceRect: Boolean,
        imageWidth: Int,
        imageHeight: Int,
        rotation: Int,
        isFrontCamera: Boolean = true,
        showEyeRect: Boolean = true
    ) {
        this.faces = faces
        this.showFaceRect = showFaceRect
        this.imageWidth = imageWidth
        this.imageHeight = imageHeight
        this.imageRotation = rotation
        this.isFrontCamera = isFrontCamera
        this.showEyeRect = showEyeRect
        needUpdateTransformation = true
        invalidate()
    }

    /**
     * 更新坐标转换矩阵
     * 将原始图像坐标系(720x720)转换为预览视图坐标系(1080x1100)
     */
    private fun updateTransformationIfNeeded() {
        if (!needUpdateTransformation) return

        transformationMatrix.reset()

        // 计算缩放比例
        val scaleX =
            previewWidth.toFloat() / (if (imageRotation % 180 == 0) imageWidth else imageHeight)
        val scaleY =
            previewHeight.toFloat() / (if (imageRotation % 180 == 0) imageHeight else imageWidth)

        // 根据相机类型和旋转角度设置变换
        if (isFrontCamera) {
            // 前置相机
            transformationMatrix.postScale(scaleX, scaleY)

            // 水平镜像
            transformationMatrix.postScale(-1f, 1f, previewWidth / 2f, previewHeight / 2f)

            // 旋转处理
            when (imageRotation) {
                90 -> transformationMatrix.postRotate(90f, previewWidth / 2f, previewHeight / 2f)
                270 -> transformationMatrix.postRotate(270f, previewWidth / 2f, previewHeight / 2f)
            }
        } else {
            // 后置相机
            transformationMatrix.postScale(scaleX, scaleY)

            // 旋转处理
            when (imageRotation) {
                90 -> transformationMatrix.postRotate(270f, previewWidth / 2f, previewHeight / 2f)
                270 -> transformationMatrix.postRotate(90f, previewWidth / 2f, previewHeight / 2f)
            }
        }

        needUpdateTransformation = false
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        if (changed) {
            needUpdateTransformation = true  // 视图大小改变时需要更新变换矩阵
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (faces.isEmpty() || previewWidth == 0 || previewHeight == 0) return

        // 更新转换矩阵
        updateTransformationIfNeeded()

        // 遍历所有检测到的人脸
        for (face in faces) {
            // 1. 绘制人脸框
            if (showFaceRect) {
                val box = face.boundingBox
                val rect = RectF(box)
                transformationMatrix.mapRect(rect)
                canvas.drawRect(rect, paint)
            }

            // 2. 绘制眼睛框
            if (showEyeRect) {
                val leftEye = face.getLandmark(com.google.mlkit.vision.face.FaceLandmark.LEFT_EYE)
                val rightEye = face.getLandmark(com.google.mlkit.vision.face.FaceLandmark.RIGHT_EYE)

                if (leftEye != null && rightEye != null) {
                    // 计算两眼之间的距离
                    val eyeDistance = Math.hypot(
                        (rightEye.position.x - leftEye.position.x).toDouble(),
                        (rightEye.position.y - leftEye.position.y).toDouble()
                    ).toFloat()

                    // 根据人脸旋转角度调整眼睛区域大小
                    val rotationY = Math.abs(face.headEulerAngleY)
                    val eyeScale = if (rotationY > 30) 0.4f else if (rotationY > 15) 0.3f else 0.2f

                    // 创建包含两只眼睛的矩形区域
                    val eyeRect =
                        if (!isFrontCamera && (imageRotation == 90 || imageRotation == 270)) {
                            // 后置摄像头且旋转90度或270度时
                            val centerX = (leftEye.position.x + rightEye.position.x) / 2f
                            val centerY = (leftEye.position.y + rightEye.position.y) / 2f

                            // 计算眼睛框的尺寸
                            val width = eyeDistance * 1.2f  // 增加宽度以更好地覆盖眼睛区域
                            val height = eyeDistance * 0.4f // 调整高度

                            RectF(
                                centerX - width / 2,   // 左边界
                                centerY - height / 2,  // 上边界
                                centerX + width / 2,   // 右边界
                                centerY + height / 2   // 下边界
                            )
                        } else {
                            // 前置摄像头或不需要旋转时
                            RectF(
                                Math.min(
                                    leftEye.position.x,
                                    rightEye.position.x
                                ) - eyeDistance * 0.3f,  // 左边界
                                Math.min(
                                    leftEye.position.y,
                                    rightEye.position.y
                                ) - eyeDistance * 0.2f,  // 上边界
                                Math.max(
                                    leftEye.position.x,
                                    rightEye.position.x
                                ) + eyeDistance * 0.3f,  // 右边界
                                Math.max(
                                    leftEye.position.y,
                                    rightEye.position.y
                                ) + eyeDistance * 0.2f   // 下边界
                            )
                        }

                    // 应用变换矩阵
                    val transformedEyeRect = RectF(eyeRect)
                    transformationMatrix.mapRect(transformedEyeRect)
                    canvas.drawRect(transformedEyeRect, paint)
                }
            }
        }
    }

    /**
     * 设置预览视图尺寸
     * @param width 预览视图宽度
     * @param height 预览视图高度
     */
    fun setPreviewSize(width: Int, height: Int) {
        previewWidth = width
        previewHeight = height
        needUpdateTransformation = true  // 预览尺寸改变时需要更新变换矩阵
        invalidate()
    }
} 